// application/service/BorrowService.java
package com.library.bookservice.application.service;

import com.library.bookservice.domain.model.Book;
import com.library.bookservice.domain.model.BorrowRecord;
import com.library.bookservice.domain.port.BookRepositoryPort;
import com.library.bookservice.domain.port.BorrowRecordRepositoryPort;
import com.library.bookservice.domain.port.BorrowServicePort;
import com.library.bookservice.domain.exception.BookNotAvailableException;
import com.library.bookservice.domain.exception.BookNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 借阅服务实现
 * 处理图书借阅和归还的业务逻辑
 */
@Service
public class BorrowService implements BorrowServicePort {

    private final BookRepositoryPort bookRepository;
    private final BorrowRecordRepositoryPort borrowRecordRepository;

    public BorrowService(BookRepositoryPort bookRepository,
                         BorrowRecordRepositoryPort borrowRecordRepository) {
        this.bookRepository = bookRepository;
        this.borrowRecordRepository = borrowRecordRepository;
    }

    @Override
    public BorrowRecord borrowBook(Long bookId, String borrowerName, String borrowerPhone) {
        // 获取图书
        Book book = bookRepository.findById(bookId);
        if (!book.canBorrow()) {
            throw new BookNotAvailableException("图书不可借阅");
        }

        // 创建借阅记录
        BorrowRecord record = new BorrowRecord(bookId, borrowerName, borrowerPhone);
        BorrowRecord savedRecord = borrowRecordRepository.save(record);

        // 更新图书库存
        book.borrowBook();
        bookRepository.save(book);

        return savedRecord;
    }

    @Override
    public BorrowRecord returnBook(Long recordId) {
        BorrowRecord record = borrowRecordRepository.findById(recordId);
        if (record.isReturned()) {
            throw new IllegalStateException("图书已归还");
        }

        // 标记为已归还
        record.markAsReturned();
        borrowRecordRepository.save(record);

        // 更新图书库存
        Book book = bookRepository.findById(record.getBookId());
        book.returnBook();
        bookRepository.save(book);

        return record;
    }

    @Override
    public List<BorrowRecord> getBorrowRecordsByBookId(Long bookId) {
        return borrowRecordRepository.findByBookId(bookId);
    }

    @Override
    public List<BorrowRecord> getBorrowRecordsByBorrower(String borrowerName) {
        return borrowRecordRepository.findByBorrowerName(borrowerName);
    }

    @Override
    public List<BorrowRecord> getActiveBorrowRecords() {
        return borrowRecordRepository.findByNotReturned();
    }
}